package com.liliya.servlet.cate;

import com.liliya.pojo.Ad;
import com.liliya.pojo.Cate;
import com.liliya.service.CateService;
import com.liliya.service.impl.AdServiceImpl;
import com.liliya.service.impl.CateServiceImpl;
import com.liliya.utils.UploadFileUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Description TODO
 * @Author hhy
 * @Date 2021/1/9 18:33
 */
@WebServlet(urlPatterns = "/cate/add")
public class CateAddServlet extends HttpServlet {
    CateService cateService = new CateServiceImpl();
    // 上传配置
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //文件名
        String fileName = "";

        //字段名字
        String cateName = "",cateDes = "",cateStyle = "";

        if (!ServletFileUpload.isMultipartContent(req)) {
            return;
        }
        String cateFilePath = "/upload/cate/";
        String uploadPath = this.getServletContext().getRealPath(cateFilePath);

        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdir();
        }

        //缓存  -- 临时文件：如果文件超过了预期的大小，那就把这个文件放到临时文件中华，过几天再删除
        String temPath = this.getServletContext().getRealPath("/WEB-INF/tem");
        System.out.println(uploadPath);
        File temFile = new File(temPath);
        if (!temFile.exists()) {
            temFile.mkdir();
        }

        //1. 创建 DiskFileItemFactory 用于限制文件大小之类的参数，如果不写的话，那就是默认值了
        DiskFileItemFactory factory = UploadFileUtil.getDiskFileItemFactory(temFile);

        //2. 获取ServletFileUpload
        ServletFileUpload upload = UploadFileUtil.getServletFileUpload(factory);

        //3. 把前端的请求封装成一个FileItem对象 （每一个表单对象）
        try {
            List<FileItem> fileItems = upload.parseRequest(req);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {//如果这个是普通的表单就正常的流程
                    String inputName = fileItem.getFieldName();
                    switch (inputName){
                        case "catename":
                            cateName = fileItem.getString("utf-8");
                            break;
                        case "catedes":
                            cateDes = fileItem.getString("utf-8");
                            break;
                        case "catestyle":
                            cateStyle = fileItem.getString("utf-8");
                    }

//                    System.out.println("表单字段的name："+fileItem.getFieldName());
//                    System.out.println("表单字段的value"+fileItem.getString("utf-8"));

                } else {//文件
                    String uploadFileName = fileItem.getName();
                    if (uploadFileName.trim().equals("") || uploadFileName == null) { //文件名不合法
                        continue;
                    }

                    //获取上传的文件名
                    fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                    String dateTime = new SimpleDateFormat("YYMMddHHmmssSSSS").format(System.currentTimeMillis());
                    fileName = dateTime + "_" + fileName;

                    //文件写入
                    fileItem.write(new File(uploadPath + "/" + fileName));
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Cate cate = new Cate();
        cate.setCatename(cateName);
        cate.setCatedes(cateDes);
        cate.setCatestyle(cateStyle);
        cate.setCateimglink(cateFilePath + fileName);
        cateService.insertCate(cate);


//        resp.sendRedirect(req.getContextPath() + cateFilePath + fileName);
        //http://localhost:8080/shop/cate/update
        resp.sendRedirect(req.getContextPath() + "/cate/update");
    }

}

